package org.dromara.pe.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.pe.domain.Achievement;
import org.dromara.pe.domain.DeviceScoreRaw;
import org.dromara.pe.domain.ScopeSetting;
import org.dromara.pe.domain.bo.*;
import org.dromara.pe.domain.vo.*;
import org.dromara.pe.mapper.StatisticMapper;
import org.dromara.pe.service.IDeviceScoreRawService;
import org.dromara.pe.service.IScopeSettingService;
import org.dromara.pe.service.IStatisticService;
import org.dromara.pe.service.ITaskInfoService;
import org.dromara.run.service.IDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author Lion Li
 * @date 2024-09-25
 */
@RequiredArgsConstructor
@Service
public class StatisticImpl implements IStatisticService {

    private IDeviceScoreRawService deviceScoreRawService;
    private ITaskInfoService taskInfoService;
    @Autowired
    private StatisticMapper baseMapper;

    private IDeptService iDeptService;
    @Autowired
    private IScopeSettingService iScopeSettingService;

    /**
     * 查询数据采集记录列表
     */

    private void queryList(StatisticBo bo, PageQuery pageQuery) {

        Date date = new Date();
        long time = date.getTime();
        TaskInfoBo taskInfoBo = new TaskInfoBo();
        List<TaskInfoVo> taskInfoVos = taskInfoService.queryList(taskInfoBo);
        List<TaskInfoVo> newTaskInfos = new ArrayList<>();
        try {
            if (CollectionUtils.isNotEmpty(taskInfoVos)) {
                for (TaskInfoVo taskInfoVo : taskInfoVos) {
                    DateFormat dateFormat = new SimpleDateFormat();
                    Long startDate = taskInfoVo.getStartDate().getTime();
                    Long endDate = taskInfoVo.getEndDate().getTime();
                    if (time >= startDate && time <= endDate) {
                        newTaskInfos.add(taskInfoVo);
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (CollectionUtils.isNotEmpty(newTaskInfos)) {
            TaskInfoVo taskInfoVo = newTaskInfos.get(0);
            List<String> strings = iDeptService.selectDeptNames("2");
            if (CollectionUtils.isNotEmpty(strings)) {
                for (String grade : strings) {
                    bo.setGrade(grade);
                    QueryWrapper<StatisticBo> lqw = buildQueryWrapper(bo);
                    List<StatisticVo> result = baseMapper.selectTopList(lqw);
                }
            }
        }
    }

    private QueryWrapper<StatisticBo> buildQueryWrapper(StatisticBo bo) {
        Map<String, Object> params = bo.getParams();
        QueryWrapper<StatisticBo> lqw = new QueryWrapper<>();
        lqw.orderBy(StringUtils.isNotBlank(bo.getRowScore()), true, "");
        lqw.orderBy(StringUtils.isNotBlank(bo.getRowSportScore()), true, "");
        lqw.last("LIMIT 0," + (StringUtils.isNotBlank(bo.getNum()) ? bo.getNum() : "10"));
//        lqw.eq(StringUtils.isNotBlank(bo.getStuNum()), "ppa.stu_num", bo.getStuNum());
//        lqw.eq(StringUtils.isNotBlank(bo.getGender()), "pmi.gender", bo.getGender());
        lqw.eq(StringUtils.isNotBlank(bo.getGrade()), "ppa.grade", bo.getGrade());
        return lqw;
    }

    public List<StatisticVo> queryLastSevenDaysData(StatisticBo bo){
        return baseMapper.selectLastSevenDaysData(bo);
    }
    public List<StatisticVo> querySexRatio(StatisticBo bo){
        QueryWrapper<StatisticBo> lqw = new QueryWrapper<>();
        Map<String, Object> params = bo.getParams();
        lqw.between(params.get("beginCompletedTime") != null && params.get("endCompletedTime") != null,
            "pdsr.completed_time",params.get("beginCompletedTime"), params.get("endCompletedTime"));
        return baseMapper.selectSexRatio(lqw);
    }
    public List<StatisticForClassVo> queryParticipationRateByStudent(StatisticBo bo){
        QueryWrapper<StatisticBo> lqw = new QueryWrapper<>();
//        lqw.like(true,"pbtc.class_name","%年级%班");
        lqw.in(CollectionUtils.isNotEmpty(bo.getClassIds()),"pbtc.class_id",bo.getClassIds());
        return baseMapper.selectParticipationRateByStudent(lqw,bo);
    }
    public List<StatisticVo> queryParticipationRateByScope(StatisticBo bo){
        QueryWrapper<StatisticBo> lqw = new QueryWrapper<>();
        lqw.like(true,"sdd.dict_type","pe_project_name");
        ScopeSettingBo scopeSettingBo=new ScopeSettingBo();
        scopeSettingBo.setIsDevice(0L);
        List<ScopeSettingVo> scopeSettingVos = iScopeSettingService.queryList(scopeSettingBo);
        if(CollectionUtils.isEmpty(scopeSettingVos)){
            throw new ServiceException("没有配置，请先配置");
        }
        List<String> sportIdList = scopeSettingVos.stream()
            .map(ScopeSettingVo::getSportId)
            .collect(Collectors.toList());
        lqw.in(true,"sdd.dict_value",sportIdList);
        return baseMapper.selectParticipationRateByScope(lqw,bo);
    }
    public Map<String ,Long> queryStudentNum(StatisticBo bo){
        QueryWrapper<StatisticBo> lqw = new QueryWrapper<>();
        Long totalNum = baseMapper.selectStudentTotalNum(lqw);
        QueryWrapper<StatisticBo> lqw2 = new QueryWrapper<>();
        lqw2.eq(true,"pmi.gender","1");
        Long girlNum = baseMapper.selectStudentTotalNum(lqw2);
        QueryWrapper<StatisticBo> lqw3 = new QueryWrapper<>();
        lqw3.eq(true,"pmi.gender","0");
        Long boyNum = baseMapper.selectStudentTotalNum(lqw3);
        QueryWrapper<StatisticBo> lqw4 = new QueryWrapper<>();
        Map<String, Object> params = bo.getParams();
        lqw.between(params.get("beginCompletedTime") != null && params.get("endCompletedTime") != null,
            "pdsr.completed_time",params.get("beginCompletedTime"), params.get("endCompletedTime"));
        Long sportNum = baseMapper.selectSportTotalNum(lqw4);
        Map<String,Long> map=new LinkedHashMap<>();
        map.put("totalNum",totalNum);
        map.put("girlNum",girlNum);
        map.put("boyNum",boyNum);
        map.put("sportNum",sportNum);
        return map;
    }

}
